package com.weacar.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.example.zhouwei.library.CustomPopWindow;
import com.gcssloop.widget.RCImageView;
import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;
import com.weacar.R;
import com.weacar.bean.BaseBean;
import com.weacar.bean.LoginBean;
import com.weacar.config.AppStatus;
import com.weacar.config.Constans;
import com.weacar.utils.AppManager;
import com.weacar.utils.AppStatusManager;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.SharedPreferenceUtil;
import com.weacar.utils.SystemUtil;
import com.weacar.utils.ToastUtil;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class SettingActivity extends TakePhotoActivity {


    // 拍照相关
    private TakePhoto takePhoto;
    private CropOptions cropOptions;  //裁剪参数
    private CompressConfig compressConfig;  //压缩参数
    private Uri imageUri;  //图片保存路径


    private CustomPopWindow mCustomPopWindow;

    @BindView(R.id.cl_main)
    ConstraintLayout cl_main;
    @BindView(R.id.rc_image_header)
    RCImageView rc_image_header;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.iv_level)
    ImageView iv_level;
    @BindView(R.id.tv_version)
    TextView tv_version;

    @OnClick({R.id.iv_back, R.id.rc_image_header, R.id.tv_nickname, R.id.tv_change_password, R.id.iv_next_password, R.id.iv_next_nickname, R.id.tv_change_nickname, R.id.iv_photot_desc, R.id.tv_photo_desc, R.id.tv_quite_login})
    public void click(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rc_image_header:
            case R.id.iv_photot_desc:
            case R.id.tv_photo_desc:
                // 拍照和相册选取
                if (android.os.Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PermissionChecker.PERMISSION_GRANTED) {
                    initPermission();
                } else {
                    initTakePhotoData();
                    showPop();
                }
                break;
            case R.id.tv_change_password:
            case R.id.iv_next_password:
                intent = new Intent(getApplicationContext(), ChangePersonInfoActivity.class);
                intent.putExtra("changePassword", "1");
                startActivity(intent);
                break;
            case R.id.tv_change_nickname:
            case R.id.iv_next_nickname:
                intent = new Intent(getApplicationContext(), ChangePersonInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_quite_login:
                SharedPreferenceUtil.setObject(getApplicationContext(), "loginBean", null);
                intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
                finish();
                break;
        }
    }

    private LoadingDialog ld;
    private LoginBean loginBean;

    public void showLoading(String loadingMessage) {
        ld = new LoadingDialog(this);
        if (loadingMessage.equals("")) {
            ld.setLoadingText("努力加载中...")
                    .show();
        } else {
            ld.setLoadingText(loadingMessage)
                    .show();
        }


    }

    public void closeLoading() {
        if (ld != null) {
            ld.close();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        if (AppStatusManager.getInstance().getAppStatus() == AppStatus.STATUS_RECYCLE) {
            //被回收，跳转到启动页面
            Intent intent = new Intent(this, SplashActivity.class);
            startActivity(intent);
            finish();
            return;
        }
        AppManager.getInstance().addActivity(this);
        ButterKnife.bind(this);
        initInfo();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (Constans.isRefreshPersonInfo) {
            LoginBean loginBean = SharedPreferenceUtil.getObject(getApplicationContext(), "loginBean");
            tv_nickname.setText(loginBean.getMsg().getNickname());
        }
    }

    public void initInfo() {
        loginBean = SharedPreferenceUtil.getObject(getApplicationContext(), "loginBean");
        tv_version.setText(SystemUtil.getAppVersion(this));

        if (loginBean != null) {
            if (loginBean.getMsg() != null && !loginBean.getMsg().getHeadimgurl().equals("")) {
                Glide.with(this).load(loginBean.getMsg().getHeadimgurl()).into(rc_image_header);
            }

            if (loginBean.getMsg() != null && loginBean.getMsg().getNickname() != null) {
                tv_nickname.setText(loginBean.getMsg().getNickname());
            }
            if (loginBean.getMsg() != null) {
                switch (loginBean.getMsg().getLevel()) {
                    case 1:
                        iv_level.setImageResource(R.mipmap.vip_putong);
                        break;
                    case 2:
                        iv_level.setImageResource(R.mipmap.vip_baijin);
                        break;
                    case 3:
                        iv_level.setImageResource(R.mipmap.vip_huangjin);
                        break;
                    case 4:
                        iv_level.setImageResource(R.mipmap.vip_heijin);
                        break;
                    case 5:
                        iv_level.setImageResource(R.mipmap.vip_zuanshi);
                        break;
                }
            }

        }
    }

    public void showPop() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_bottom_photo, null);
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAtLocation(cl_main, Gravity.BOTTOM, 0, 0);

        TextView tv_take_photo = contentView.findViewById(R.id.tv_take_photo);
        TextView tv_gallery = contentView.findViewById(R.id.tv_gallery);
        TextView tv_cancle = contentView.findViewById(R.id.tv_cancle);

        tv_take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (takePhoto != null) {
                    imageUri = getImageCropUri();
                    //拍照并裁剪
                    takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
                    //仅仅拍照不裁剪
                    //takePhoto.onPickFromCapture(imageUri);
                }
            }
        });

        tv_gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (takePhoto != null) {
                    imageUri = getImageCropUri();
                    //拍照并裁剪
                    takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                    //仅仅拍照不裁剪
                    //takePhoto.onPickFromGallery();
                }
            }
        });

        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCustomPopWindow.dissmiss();
            }
        });
    }


    /**
     * 图片上传接口
     *
     * @param path 图片地址
     */
    public void upLoadImage(String path) {

        if (!NetWorkUtil.isNetworkAvailable(this)) {
            ToastUtil.showShort(getApplicationContext(), "当前网络不可用");
            return;
        }

        showLoading("头像更换中...");

        RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.upload_url);
        params.setCacheMaxAge(0);
        params.setMultipart(true);
        params.addBodyParameter("file", new File(path), "multipart/form-data");
        LogUtils.d("upload_url = " + params.getUri());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d("result = " + result);
                try {
                    // 图片上传成功
                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
                    boolean isSuccess = (boolean) jsonObject.get("uploaded");
                    if (isSuccess) {
                        String head_img = (String) jsonObject.get("url");
                        if (head_img != null && !head_img.equals("")) {
                            // 图片上传成功调用修改头像接口
                            changeHeaderImg(head_img);
                        }
                    } else {
                        ToastUtil.showShort(getApplicationContext(), jsonObject.get("msg").toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeLoading();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                closeLoading();
            }

            @Override
            public void onFinished() {
                closeLoading();
            }
        });
    }


    /**
     * 修改头像接口
     *
     * @param imgUrl
     */
    public void changeHeaderImg(final String imgUrl) {

        try {
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.change_header_img_url);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("imgurl", imgUrl);
            js_request.put("token", loginBean.getMsg().getToken());

            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));

            LogUtils.d("change_header_url = " + params.getUri());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    closeLoading();
                    LogUtils.d("change_header_result = " + result);
                    try {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                        if (baseBean != null && baseBean.getCode() == 1) {
                            ToastUtil.showShort(getApplicationContext(), "头像更换成功");
                            // 更新本地个人信息
                            loginBean.getMsg().setHeadimgurl(imgUrl);
                            SharedPreferenceUtil.setObject(getApplicationContext(), "loginBean", loginBean);
                            // 回到我的页面刷新个人信息
                            Constans.isRefreshPersonInfo = true;
                        } else {
                            // 错误信息提示
                            if (baseBean != null) {
                                try {
                                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(DesUtil.decrypt(baseBean.getData()));
                                    ToastUtil.showShort(getApplicationContext(), jsonObject.get("msg").toString());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                ToastUtil.showShort(getApplicationContext(), "系统异常");
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    closeLoading();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    closeLoading();
                }

                @Override
                public void onFinished() {
                    closeLoading();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //申请相关权限
    public void initPermission() {
        // 申请权限。
        AndPermission.with(this)
                .permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).onGranted(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                initTakePhotoData();
            }
        }).onDenied(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                Toast.makeText(getApplicationContext(), "拍照上传图片功能被禁止，被禁止的功能将无法使用", Toast.LENGTH_SHORT).show();
            }
        }).start();
    }


    // 初始化数据
    public void initTakePhotoData() {
        takePhoto = getTakePhoto();
        //设置裁剪参数
        cropOptions = new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(false).create();
        //设置压缩参数
        compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(800).create();
        takePhoto.onEnableCompress(compressConfig, true); //设置为需要压缩
    }

    //获得照片的输出保存Uri
    private Uri getImageCropUri() {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        return Uri.fromFile(file);
    }


    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        String iconPath = result.getImage().getOriginalPath();
        // 上传图片到服务器
        upLoadImage(iconPath);
        //Toast显示图片路径
        // Toast.makeText(this, "imagePath:" + iconPath, Toast.LENGTH_SHORT).show();
        Glide.with(this).load(iconPath).into(rc_image_header);
        mCustomPopWindow.dissmiss();
    }


    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
        mCustomPopWindow.dissmiss();
    }


}
